import { ref } from "vue";

export function useGoodButtonHook() {
  const buttonLoading = ref(false);
  const buttonDisabled = ref(false);
  async function doButtonAction(action: (end: Function) => void) {
    //执行开始就关闭点击功能
    buttonDisabled.value = true;
    //延迟800ms打开加载框，并取消buttonDisabled避免闪烁
    const task1 = setTimeout(function () {
      buttonLoading.value = true;
      buttonDisabled.value = false;
    }, 800);
    //5秒自动关闭
    const task2 = setTimeout(function () {
      buttonLoading.value = false;
      buttonDisabled.value = false;
    }, 5000);
    action(confirmEnd);
    function confirmEnd() {
      clearTimeout(task1);
      clearTimeout(task2);
      buttonLoading.value = false;
      buttonDisabled.value = false;
    }
  }
  return {
    buttonLoading,
    doButtonAction,
    buttonDisabled,
  };
}
